package cmcc.dbi.execUtil;

import cmcc.dbi.dto.ShellQueryDTO;
import cmcc.dbi.entity.InspectionItemRecord;
import cmcc.dbi.exception.ExecutEngineExcption;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.JSchException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExeShellUtil {
    private String ShellResKey = "resValue";

    public JSONArray getTargetResult(List<InspectionItemRecord> scriptsLists, ShellQueryDTO shellQueryDTO) throws JSchException {
        //建立连接
        exeJschUtil exeJschUtil = new exeJschUtil(shellQueryDTO);
        //建立连接
        exeJschUtil.getConnect();

        //用于保存所有巡检项结果
        JSONArray queryAllResult = new JSONArray();
        //分别执行各个脚本
        for (InspectionItemRecord scriptsList : scriptsLists) {
            //保存单个巡检项对应的结果
            JSONObject querySingleResult = new JSONObject();
            List<Map<String, Object>> lisTmp = new ArrayList<>();
            Map<String, Object> tmp = new HashMap<>();
            //获取当前巡检项的shell脚本
            String shellCom = scriptsList.getScript();
            //执行某个脚本
            try{

                //执行语句
                String resultStr = exeJschUtil.exectueNormalCmd(shellCom);
                log.info("The SqlCom execute success - > {}",resultStr);
                //结果只有一行，取其中第一行即可
                tmp.put(ShellResKey,resultStr);
                lisTmp.add(tmp);
            }catch (ExecutEngineExcption e) {
                //执行出问题
                log.info("The SqlCom execute failed");
                //记录错误信息
                tmp.put("error_info",String.valueOf(e));
                log.info("error_info："+ e);
                lisTmp.add(tmp);
            }
            querySingleResult.put("item_id", scriptsList.getItemId());
            querySingleResult.put("jdbc_result", lisTmp);
            queryAllResult.add(querySingleResult);
        }
        return queryAllResult;
    }
}
